package com.terracloud.common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author chenhainan
 * @since 2025/10/13
 */
public class AsyncUtils {

    private AsyncUtils() {
    }

    public static void joinAll(Runnable... runnableArray) {
        joinAll(Arrays.asList(runnableArray));
    }

    public static void joinAll(List<Runnable> runnableList) {
        if (runnableList == null || runnableList.isEmpty()) {
            return;
        }
        if (runnableList.size() == 1) {
            runnableList.getFirst().run();
            return;
        }
        try (final var executorService = Executors.newVirtualThreadPerTaskExecutor()){
            runnableList.forEach(executorService::execute);
        }
    }

    public static <R> List<R> awaitAll(List<Callable<R>> callableList) throws Exception {
        if (callableList == null || callableList.isEmpty()) {
            return Collections.emptyList();
        }
        if (callableList.size() == 1) {
            return Collections.singletonList(callableList.getFirst().call());
        }
        final var resultList = new ArrayList<R>();
        try (final var executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (var future : executorService.invokeAll(callableList)) {
                resultList.add(future.get());
            }
        }
        return resultList;
    }

}
